<?php

namespace EthanZ\HyperfExt\Utils;

use EthanZ\HyperfExt\Constants\Code;
use EthanZ\HyperfExt\Exception\BaseException;
use Hyperf\Utils\Str;

/**
 * rpc相关
 */
class LoadRpc
{


    protected static $rpcServer = [
        'UserServiceServer'
    ];


    protected static $rpcDependencies = [
        \EthanZ\HyperfExt\JsonRpc\Inter\UserServiceInter::class => \EthanZ\HyperfExt\JsonRpc\Client\UserServiceClient::class,
    ];


    /**
     * 获取rpc消费者配置
     *
     * @return array
     */
    public static function rpcConsumers(): array
    {
        $consumers = [];

        foreach (self::$rpcServer as $v) {
            $upperName = Str::upper(Str::snake($v));
            $consumers[] = [
                'name'  => $v,
                'nodes' => [
                    ['host' => (string)env($upperName . '_HOST'), 'port' => (int)env($upperName . '_PORT')],
                ],
            ];
        }

        return $consumers;
    }


    /**
     * 获取rpc依赖关系
     *
     * @return array
     */
    public static function rpcDependencies(): array
    {
        return self::$rpcDependencies;
    }


    /**
     * rpc返回数据整理
     *
     * @param mixed $data
     *
     * @return mixed
     */
    public static function rpcDataBuild(mixed $data): mixed
    {
        if (!isset($data['code']) || $data['code'] != Code::SUCCESS[0]) {
            throw new BaseException(Code::ERROR, 1);
        }

        return $data['data'] ?? '';
    }
}
